package com.study.example.gameserver.module.scene.bt.node;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.node.impl.ActionNode;
import com.study.example.gameserver.module.scene.domain.SceneMap;
import com.study.example.gameserver.module.scene.entity.IPlayerEntity;
import com.study.example.gameserver.module.scene.entity.impl.Monster;
import com.study.example.gameserver.module.scene.service.SceneService;

/**
 * 攻击敌人节点（主动攻击）
 */
public class AttackEnemy extends ActionNode {

    /** 攻击冷却时间（毫秒） */
    private static final long ATTACK_COOLDOWN = 1000L;

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        Monster monster = context.getOwner();
        if (monster == null) {
            return BTNodeStatus.FAILURE;
        }

        SceneMap sceneMap = context.get("SceneMap", SceneMap.class);
        if (sceneMap == null) {
            return BTNodeStatus.FAILURE;
        }

        long targetId = monster.getTargetId();
        if (targetId <= 0) {
            return BTNodeStatus.FAILURE;
        }

        IPlayerEntity target = sceneMap.getPlayers().get(targetId);
        if (target == null || !target.isAlive()) {
            monster.setTargetId(0L);
            return BTNodeStatus.FAILURE;
        }

        // 冷却时间检查
        Long lastAtkTime = context.get("LastAtkTime", Long.class);
        if (lastAtkTime != null && now - lastAtkTime < ATTACK_COOLDOWN) {
            // 还在冷却中
            return BTNodeStatus.RUNNING;
        }

        // 执行攻击
        SceneService sceneService = context.get("SceneMapService", SceneService.class);
        if (sceneService == null) {
            return BTNodeStatus.FAILURE;
        }

        sceneService.monsterAttack(sceneMap, monster, target);
        context.put("LastAtkTime", now);

        // 如果目标死了，清除目标锁定
        if (!target.isAlive()) {
            monster.setTargetId(0L);
        }

        return BTNodeStatus.RUNNING;
    }

    @Override
    public void initParams(String name, String value) {
        // 可扩展配置参数（例如冷却时间）
    }

    @Override
    public String toString() {
        return "AttackEnemy";
    }
}
